/**
 * This file is part of CommaTuner.
 * Copyright 2011 Gabriel G Mendonça (gabrielgmendonca@gmail.com)
 * 
 * CommaTuner is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * CommaTuner is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with CommaTuner.  If not, see <http://www.gnu.org/licenses/>.
 */

package br.mendonca.audio.analysis;

import java.nio.ByteBuffer;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;

/**
 * Wrapper for the android.media.AudioRecord class.
 * 
 * @author gmendonca
 */
public class AudioRecorder {

	private AudioRecord audioRecord;
	private boolean running;

	/**
	 * Constructor.
	 * 
	 * @param sampleRate
	 *            The sample rate (e.g. 44100 Hz).
	 * @param bufferSize
	 *            The size of the recording buffer in bytes.
	 */
	public AudioRecorder(int sampleRate, int bufferSize) {
		audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
				sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO,
				AudioFormat.ENCODING_PCM_16BIT, bufferSize);

		Log.d("CommaTuner", "Buffer Size: " + bufferSize);
	}

	/**
	 * Reads the mic input and writes to a buffer.
	 * 
	 * @param buffer
	 *            The buffer that will store the samples.
	 * @param bufferSize
	 *            The max number of bytes to be read.
	 * @return The number of bytes that were read.
	 */
	public int read(ByteBuffer buffer, int bufferSize) {
		int samplesRead = audioRecord.read(buffer, bufferSize);

		Log.d("CommaTuner", "Samples Read: " + samplesRead);

		return samplesRead;
	}

	/**
	 * Starts recording audio. Must be called before the first call to 'read'.
	 */
	public void start() {
		if (!running) {
			audioRecord.startRecording();
			running = true;
		}
	}

	/**
	 * Stops recording audio.
	 */
	public void stop() {
		if (running) {
			audioRecord.stop();
			running = false;
		}
	}

	/**
	 * Releases the allocated memory.
	 */
	public void destroy() {
		stop();
		audioRecord.release();
	}

}
